package com.young.shop.controller;

import com.young.shop.pojo.entity.User;
import com.young.shop.service.UserService;
import com.young.shop.service.impl.UserServiceImple;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/login")
public class LoginController extends BaseController {
    @Override
    protected void doGet(HttpServletRequest req , HttpServletResponse resp) throws ServletException, IOException {
//        System.out.println("doGet");
        doPost(req, resp);
    }

    private UserService userService=new UserServiceImple();
    @Override
    protected void doPost(HttpServletRequest req , HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doPost");

        String ID = req.getParameter("userName");
        User user=null;
        if (!ID.contains("@")){
            user = convertUserNameToUser(req);
            try{
                User dbUser = userService.checkLoginByUserName(user);

                req.getSession().setAttribute("client",dbUser);
                writerSucccessBaseRespVoToResponse(resp,dbUser);
            }catch (RuntimeException e){
                writerFailedBaseRespVoToResponse(resp,e);
            }
        }else {
            User user1 = convertEmailToUser(req);
            try{
                User dbUser = userService.checkRegisterByEmail(user1);
                req.getSession().setAttribute("client",dbUser);
                writerSucccessBaseRespVoToResponse(resp,dbUser);
            }catch (RuntimeException e){
                writerFailedBaseRespVoToResponse(resp,e);
            }
        }



        //校验参数
        /*try{
            User dbUser = userService.checkLogin(user);
            System.out.println("第二次"+dbUser);
            req.getSession().setAttribute("username",dbUser.getUserName());
            writerSucccessBaseRespVoToResponse(resp,dbUser);
        }catch (RuntimeException e){
            writerFailedBaseRespVoToResponse(resp,e);
        }*/

    }

    private User convertEmailToUser(HttpServletRequest req) {
        String email = req.getParameter("userName");
        String password = req.getParameter("password");
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        return user;
    }

    /*private void validateParams(User dbUser) {
        boolean b = userService.existsByUserEmail(dbUser);
        if (!b){
            throw new RuntimeException("用户名不存在");
        }
    }*/

    private User convertUserNameToUser(HttpServletRequest req) {
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        return user;
    }
}
